"""
战斗系统模块
处理玩家与怪物的战斗逻辑
"""
import random
from typing import Tuple, Optional, Dict
from .game_core import Player, Monster, GameCore

class BattleResult:
    """战斗结果类"""
    def __init__(self, victory: bool, message: str, exp_gained: int = 0, items_gained: Dict[str, int] = None):
        self.victory = victory
        self.message = message
        self.exp_gained = exp_gained
        self.items_gained = items_gained or {}

class BattleSystem:
    """战斗系统"""
    
    def __init__(self, game_core: GameCore):
        self.game_core = game_core
    
    def start_battle(self, player: Player, monster: Monster) -> BattleResult:
        """开始战斗"""
        battle_log = [f"遭遇了{monster.name}（等级{monster.level}）！"]
        
        # 复制怪物数据，避免修改原始数据
        monster_hp = monster.hp
        player_hp = player.hp
        
        # 战斗循环
        round_count = 0
        max_rounds = 20  # 最大回合数，防止无限循环
        
        while monster_hp > 0 and player_hp > 0 and round_count < max_rounds:
            round_count += 1
            battle_log.append(f"\n第{round_count}回合：")
            
            # 玩家攻击
            player_damage = self._calculate_damage(player.attack, monster.defense)
            monster_hp -= player_damage
            battle_log.append(f"你对{monster.name}造成了{player_damage}点伤害")
            
            if monster_hp <= 0:
                # 玩家胜利
                battle_log.append(f"{monster.name}被击败了！")
                return self._handle_victory(player, monster, battle_log)
            
            # 怪物攻击
            monster_damage = self._calculate_damage(monster.attack, player.defense)
            player_hp -= monster_damage
            battle_log.append(f"{monster.name}对你造成了{monster_damage}点伤害")
            
            if player_hp <= 0:
                # 玩家失败
                battle_log.append("你被击败了...")
                return self._handle_defeat(player, battle_log)
            
            battle_log.append(f"你的生命值：{player_hp}/{player.max_hp}")
            battle_log.append(f"{monster.name}的生命值：{monster_hp}/{monster.hp}")
        
        # 超时平局（视为失败）
        if round_count >= max_rounds:
            battle_log.append("战斗持续太久，你力竭败北...")
            return self._handle_defeat(player, battle_log)
        
        # 理论上不会到达这里
        return BattleResult(False, "\n".join(battle_log))
    
    def _calculate_damage(self, attack: int, defense: int) -> int:
        """计算伤害"""
        base_damage = max(1, attack - defense)  # 至少造成1点伤害
        # 添加随机因素，伤害在80%-120%之间波动
        damage_multiplier = random.uniform(0.8, 1.2)
        final_damage = int(base_damage * damage_multiplier)
        return max(1, final_damage)
    
    def _handle_victory(self, player: Player, monster: Monster, battle_log: list) -> BattleResult:
        """处理胜利"""
        # 获得经验
        exp_gained = monster.exp_reward
        player.exp += exp_gained
        battle_log.append(f"获得{exp_gained}点修为！")
        
        # 物品掉落
        items_gained = {}
        for item_name, drop_rate in monster.item_drops.items():
            if random.random() < drop_rate:
                items_gained[item_name] = 1
                player.add_item(item_name, 1)
                battle_log.append(f"获得了{item_name}！")
        
        # 恢复部分生命值（胜利奖励）
        heal_amount = min(20, player.max_hp - player.hp)
        if heal_amount > 0:
            player.hp += heal_amount
            battle_log.append(f"战斗胜利，恢复{heal_amount}点生命值")
        
        return BattleResult(
            victory=True,
            message="\n".join(battle_log),
            exp_gained=exp_gained,
            items_gained=items_gained
        )
    
    def _handle_defeat(self, player: Player, battle_log: list) -> BattleResult:
        """处理失败"""
        battle_log.append("\n💀 你在战斗中败北，魂归九泉...")
        battle_log.append("🔄 重新投胎转世，一切从头开始...")
        
        # 重置玩家到新手状态
        player.reset_to_newbie()
        
        battle_log.append("✨ 你已重生在清河镇，境界、物品、进度全部重置")
        
        return BattleResult(
            victory=False,
            message="\n".join(battle_log)
        )
    
    def get_encounter_chance(self, area_name: str) -> float:
        """获取区域遇怪概率"""
        # 根据区域危险程度设置不同的遇怪概率
        encounter_rates = {
            "清河镇": 0.15,      # 15%
            "青城": 0.20,        # 20%
            "灵蝶谷": 0.25,      # 25%
            "鹅城": 0.22,        # 22%
            "灵泉洞府": 0.28,    # 28%
            "天机阁": 0.30,      # 30%
            "古塔遗迹": 0.35,    # 35%
            "仙市坊": 0.25,      # 25%
            "藏书楼": 0.30,      # 30%
            "虚空秘境": 0.40,    # 40%
            "云霄宫": 0.35,      # 35%
            "禁书区": 0.38,      # 38%
            "混沌虚空": 0.45,    # 45%
            "九天云海": 0.42,    # 42%
            "时光殿": 0.50,      # 50%
        }
        return encounter_rates.get(area_name, 0.25)  # 默认25%
    
    def get_random_monster(self, area_name: str) -> Optional[Monster]:
        """从指定区域随机获取一个怪物"""
        monsters = self.game_core.monsters.get(area_name, [])
        if not monsters:
            return None
        return random.choice(monsters)